import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:video_player/video_player.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers/src/source.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:webview_flutter/webview_flutter.dart';

/// 文件类型枚举
enum FileType {
  image,
  video,
  audio,
  pdf,
  word,
  excel,
  markdown,
  html,
  text,
  unknown,
}

/// 文件预览配置类
class FilePreviewConfig {
  final String title;
  final bool showControls;
  final bool autoPlay;
  final double aspectRatio;

  const FilePreviewConfig({
    this.title = '',
    this.showControls = true,
    this.autoPlay = false,
    this.aspectRatio = 16 / 9,
  });
}

/// 文件信息类
class FileInfo {
  final String path;
  final String? name;
  final FileType? type;
  final FilePreviewConfig? config;

  FileInfo({
    required this.path,
    this.name,
    this.type,
    this.config,
  });
}

/// 通用文件预览组件
class FilePreviewWidget extends StatefulWidget {
  /// 单个文件信息
  final FileInfo? file;
  
  /// 文件列表（用于多图片预览等场景）
  final List<FileInfo>? files;
  
  /// 当前显示的文件索引
  final int initialIndex;
  
  /// 加载占位图
  final Widget? loadingWidget;
  
  /// 错误占位图
  final Widget? errorWidget;
  
  /// 预览完成回调
  final Function()? onPreviewComplete;
  
  const FilePreviewWidget({
    Key? key,
    this.file,
    this.files,
    this.initialIndex = 0,
    this.loadingWidget,
    this.errorWidget,
    this.onPreviewComplete,
  }) : super(key: key);

  @override
  State<FilePreviewWidget> createState() => _FilePreviewWidgetState();
}

class _FilePreviewWidgetState extends State<FilePreviewWidget> {
  int _currentIndex = 0;
  bool _isLoading = true;
  String? _error;
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex ?? 0;
    _pageController = PageController(initialPage: _currentIndex);
    _loadFile();
  }

  @override
  void didUpdateWidget(covariant FilePreviewWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.files != oldWidget.files || widget.file != oldWidget.file) {
      _loadFile();
    }
  }

  Future<void> _loadFile() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      // 模拟文件加载
      await Future.delayed(const Duration(milliseconds: 500));
      
      // 在实际应用中，这里可以根据文件类型进行不同的加载逻辑
      
      setState(() {
        _isLoading = false;
      });
      
      if (widget.onPreviewComplete != null) {
        widget.onPreviewComplete!();
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _error = e.toString();
      });
    }
  }

  List<FileInfo> _getFiles() {
    if (widget.files != null && widget.files!.isNotEmpty) {
      return widget.files!;
    }
    if (widget.file != null) {
      return [widget.file!];
    }
    return [];
  }

  FileType _getFileType(FileInfo file) {
    if (file.type != null) {
      return file.type!;
    }

    final path = file.path.toLowerCase();
    if (path.endsWith('.jpg') || path.endsWith('.jpeg') || path.endsWith('.png') || 
        path.endsWith('.gif') || path.endsWith('.webp') || path.endsWith('.bmp')) {
      return FileType.image;
    } else if (path.endsWith('.mp4') || path.endsWith('.avi') || path.endsWith('.mov') ||
               path.endsWith('.wmv') || path.endsWith('.mkv')) {
      return FileType.video;
    } else if (path.endsWith('.mp3') || path.endsWith('.wav') || path.endsWith('.aac') ||
               path.endsWith('.flac') || path.endsWith('.ogg')) {
      return FileType.audio;
    } else if (path.endsWith('.pdf')) {
      return FileType.pdf;
    } else if (path.endsWith('.doc') || path.endsWith('.docx')) {
      return FileType.word;
    } else if (path.endsWith('.xls') || path.endsWith('.xlsx')) {
      return FileType.excel;
    } else if (path.endsWith('.md') || path.endsWith('.markdown')) {
      return FileType.markdown;
    } else if (path.endsWith('.html') || path.endsWith('.htm')) {
      return FileType.html;
    } else if (path.endsWith('.txt')) {
      return FileType.text;
    }
    return FileType.unknown;
  }

  Widget _buildContent(FileInfo file) {
    final fileType = _getFileType(file);
    final config = file.config ?? const FilePreviewConfig();

    switch (fileType) {
      case FileType.image:
        return _buildImagePreview(file, config);
      case FileType.video:
        return _buildVideoPreview(file, config);
      case FileType.audio:
        return _buildAudioPreview(file, config);
      case FileType.pdf:
        return _buildPdfPreview(file, config);
      case FileType.word:
        return _buildWordPreview(file, config);
      case FileType.excel:
        return _buildExcelPreview(file, config);
      case FileType.markdown:
        return _buildMarkdownPreview(file, config);
      case FileType.html:
        return _buildHtmlPreview(file, config);
      case FileType.text:
        return _buildTextPreview(file, config);
      default:
        return _buildUnknownPreview(file, config);
    }
  }

  Widget _buildImagePreview(FileInfo file, FilePreviewConfig config) {
    return Center(
      child: Image.network(
        file.path,
        fit: BoxFit.contain,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return widget.loadingWidget ??
                 const Center(child: CircularProgressIndicator());
        },
        errorBuilder: (context, error, stackTrace) {
          return widget.errorWidget ??
                 const Center(child: Icon(Icons.image_not_supported_outlined));
        },
      ),
    );
  }

  Widget _buildVideoPreview(FileInfo file, FilePreviewConfig config) {
    return _VideoPlayerWidget(
      url: file.path,
      autoPlay: config.autoPlay,
      showControls: config.showControls,
      aspectRatio: config.aspectRatio,
    );
  }

  Widget _buildAudioPreview(FileInfo file, FilePreviewConfig config) {
    return _AudioPlayerWidget(
      url: file.path,
      title: config.title.isEmpty ? file.name ?? '音频预览' : config.title,
      autoPlay: config.autoPlay,
    );
  }

  Widget _buildPdfPreview(FileInfo file, FilePreviewConfig config) {
    return SfPdfViewer.network(
      file.path,
      enableDoubleTapZooming: true,
      enableTextSelection: true,
      enableDocumentLinkAnnotation: true,
    );
  }

  Widget _buildWordPreview(FileInfo file, FilePreviewConfig config) {
    // Word文档预览占位
    return Container(
      padding: const EdgeInsets.all(20),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children:
           [const Icon(Icons.description, size: 64, color: Colors.blue),
            Text(config.title.isEmpty ? file.name ?? 'Word文档' : config.title, 
                 style: const TextStyle(fontSize: 18))],
        ),
      ),
    );
  }

  Widget _buildExcelPreview(FileInfo file, FilePreviewConfig config) {
    // Excel文档预览占位
    return Container(
      padding: const EdgeInsets.all(20),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children:
           [const Icon(Icons.table_chart, size: 64, color: Colors.green),
            Text(config.title.isEmpty ? file.name ?? 'Excel文档' : config.title, 
                 style: const TextStyle(fontSize: 18))],
        ),
      ),
    );
  }

  Widget _buildMarkdownPreview(FileInfo file, FilePreviewConfig config) {
    return FutureBuilder<String>(
      future: _loadFileContent(file.path),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return widget.loadingWidget ?? const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError || !snapshot.hasData) {
          return widget.errorWidget ?? const Center(child: Icon(Icons.error_outline));
        }
        return Markdown(
          data: snapshot.data!,
          selectable: true,
          padding: const EdgeInsets.all(16),
        );
      },
    );
  }

  Widget _buildHtmlPreview(FileInfo file, FilePreviewConfig config) {
    return WebViewWidget(
      controller: WebViewController()
        ..setJavaScriptMode(JavaScriptMode.unrestricted)
        ..setBackgroundColor(const Color(0x00000000))
        ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              // 更新加载进度
            },
            onPageStarted: (String url) {},
            onPageFinished: (String url) {},
            onWebResourceError: (WebResourceError error) {},
          ),
        )
        ..loadRequest(Uri.parse(file.path)),
    );
  }

  Widget _buildTextPreview(FileInfo file, FilePreviewConfig config) {
    return FutureBuilder<String>(
      future: _loadFileContent(file.path),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return widget.loadingWidget ?? const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError || !snapshot.hasData) {
          return widget.errorWidget ?? const Center(child: Icon(Icons.error_outline));
        }
        return SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: SelectableText(
            snapshot.data!,
            style: const TextStyle(fontSize: 16),
          ),
        );
      },
    );
  }

  Widget _buildUnknownPreview(FileInfo file, FilePreviewConfig config) {
    // 未知文件类型预览
    return Container(
      padding: const EdgeInsets.all(20),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children:
           [const Icon(Icons.insert_drive_file, size: 64, color: Colors.grey),
            Text(config.title.isEmpty ? file.name ?? '未知文件' : config.title, 
                 style: const TextStyle(fontSize: 18))],
        ),
      ),
    );
  }

  // 加载文件内容
  Future<String> _loadFileContent(String path) async {
    try {
      // 这里需要根据path是网络地址还是本地路径进行不同的处理
      // 简单起见，这里假设是网络地址
      if (path.startsWith('http')) {
        // 在实际应用中，这里应该使用dio等网络库获取文件内容
        // 这里返回模拟数据
        return '这是模拟的文件内容';
      } else {
        // 本地文件
        final file = File(path);
        if (await file.exists()) {
          return await file.readAsString();
        }
        return '文件不存在';
      }
    } catch (e) {
      return '读取文件失败: $e';
    }
  }

  @override
  Widget build(BuildContext context) {
    final files = _getFiles();
    
    if (files.isEmpty) {
      return const Center(child: Text('没有要预览的文件'));
    }

    if (_isLoading) {
      return widget.loadingWidget ?? const Center(child: CircularProgressIndicator());
    }

    if (_error != null) {
      return widget.errorWidget ?? Center(child: Text('加载失败: $_error'));
    }

    // 多文件预览（主要用于图片）
    if (files.length > 1) {
      return Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.black,
          iconTheme: const IconThemeData(color: Colors.white),
          title: Text(
            files[_currentIndex].name ?? '',
            style: const TextStyle(color: Colors.white),
          ),
        ),
        body: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  child: PageView.builder(
                    itemCount: files.length,
                    controller: _pageController,
                    physics: const AlwaysScrollableScrollPhysics(),
                    scrollDirection: Axis.horizontal,
                    pageSnapping: true,
                    onPageChanged: (index) {
                      setState(() {
                        _currentIndex = index;
                      });
                    },
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: _buildContent(files[index]),
                      );
                    },
                  ),
                ),
                // 页码指示器
                Container(
                  padding: const EdgeInsets.all(8.0),
                  color: Colors.black,
                  child: Text(
                    '${_currentIndex + 1}/${files.length}',
                    style: const TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
            // Web端左右切换按钮
            if (kIsWeb)
              ...[
                Positioned(
                  left: 16,
                  top: MediaQuery.of(context).size.height / 2 - 28,
                  child: FloatingActionButton(
                    backgroundColor: Colors.black.withOpacity(0.5),
                    foregroundColor: Colors.white,
                    onPressed: _currentIndex > 0
                        ? () => _pageController.previousPage(
                              duration: const Duration(milliseconds: 300),
                              curve: Curves.ease,
                            )
                        : null,
                    child: const Icon(Icons.chevron_left),
                  ),
                ),
                Positioned(
                  right: 16,
                  top: MediaQuery.of(context).size.height / 2 - 28,
                  child: FloatingActionButton(
                    backgroundColor: Colors.black.withOpacity(0.5),
                    foregroundColor: Colors.white,
                    onPressed: _currentIndex < files.length - 1
                        ? () => _pageController.nextPage(
                              duration: const Duration(milliseconds: 300),
                              curve: Curves.ease,
                            )
                        : null,
                    child: const Icon(Icons.chevron_right),
                  ),
                ),
              ],
          ],
        ),
      );
    }

    // 单文件预览
    return _buildContent(files.first);
  }
}

/// 视频播放器组件
class _VideoPlayerWidget extends StatefulWidget {
  final String url;
  final bool autoPlay;
  final bool showControls;
  final double aspectRatio;

  const _VideoPlayerWidget({
    required this.url,
    required this.autoPlay,
    required this.showControls,
    required this.aspectRatio,
  });

  @override
  State<_VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<_VideoPlayerWidget> {
  late VideoPlayerController _controller;
  late Future<void> _initializeVideoPlayerFuture;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.networkUrl(Uri.parse(widget.url));
    _initializeVideoPlayerFuture = _controller.initialize().then((_) {
      if (widget.autoPlay) {
        _controller.play();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initializeVideoPlayerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return AspectRatio(
            aspectRatio: widget.aspectRatio,
            child: Stack(
              children: [
                VideoPlayer(_controller),
                if (widget.showControls) VideoProgressIndicator(_controller, allowScrubbing: true),
                if (widget.showControls) _VideoControlsOverlay(controller: _controller),
              ],
            ),
          );
        } else {
          return AspectRatio(
            aspectRatio: widget.aspectRatio,
            child: const Center(child: CircularProgressIndicator()),
          );
        }
      },
    );
  }
}

/// 视频控制覆盖层
class _VideoControlsOverlay extends StatelessWidget {
  final VideoPlayerController controller;

  const _VideoControlsOverlay({required this.controller});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        controller.value.isPlaying ? controller.pause() : controller.play();
      },
      child: Center(
        child: Icon(
          controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          color: Colors.white,
          size: 64,
        ),
      ),
    );
  }
}

/// 音频播放器组件
class _AudioPlayerWidget extends StatefulWidget {
  final String url;
  final String title;
  final bool autoPlay;

  const _AudioPlayerWidget({
    required this.url,
    required this.title,
    required this.autoPlay,
  });

  @override
  State<_AudioPlayerWidget> createState() => _AudioPlayerWidgetState();
}

class _AudioPlayerWidgetState extends State<_AudioPlayerWidget> {
  late AudioPlayer _player;
  PlayerState _playerState = PlayerState.stopped;
  Duration _duration = Duration.zero;
  Duration _position = Duration.zero;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initPlayer();
  }

  Future<void> _initPlayer() async {
    _player = AudioPlayer();

    _player.onPlayerStateChanged.listen((state) {
      setState(() {
        _playerState = state;
      });
    });

    _player.onDurationChanged.listen((newDuration) {
      setState(() {
        _duration = newDuration;
      });
    });

    _player.onPositionChanged.listen((newPosition) {
      setState(() {
        _position = newPosition;
      });
    });

    _player.onPlayerComplete.listen((_) {
      setState(() {
        _position = _duration;
      });
    });

    try {
      await _player.setSourceUrl(widget.url);
      setState(() {
        _isLoading = false;
      });
      if (widget.autoPlay) {
        await _player.play(UrlSource(widget.url));
      }
    } catch (e) {
      print('Error loading audio: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    _player.dispose();
    super.dispose();
  }

  String _formatDuration(Duration duration) {
    final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
    final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
    return '$minutes:$seconds';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.audiotrack, size: 64, color: Colors.blue),
          const SizedBox(height: 16),
          Text(widget.title, style: const TextStyle(fontSize: 18)),
          const SizedBox(height: 20),
          if (_isLoading)
            const CircularProgressIndicator()
          else
            Column(
              children: [
                Slider(
                  min: 0,
                  max: _duration.inMilliseconds.toDouble(),
                  value: _position.inMilliseconds.toDouble(),
                  onChanged: (value) {
                    _player.seek(Duration(milliseconds: value.toInt()));
                  },
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(_formatDuration(_position)),
                    Text(_formatDuration(_duration)),
                  ],
                ),
                IconButton(
                  icon: Icon(
                    _playerState == PlayerState.playing
                        ? Icons.pause_circle_filled
                        : Icons.play_circle_filled,
                  ),
                  iconSize: 64,
                  onPressed: () {
                    if (_playerState == PlayerState.playing) {
                      _player.pause();
                    } else {
                      _player.play(UrlSource(widget.url));
                    }
                  },
                ),
              ],
            ),
        ],
      ),
    );
  }
}

/// 文件预览弹窗
class FilePreviewDialog extends StatelessWidget {
  final FileInfo? file;
  final List<FileInfo>? files;
  final int initialIndex;
  final bool fullScreen;

  const FilePreviewDialog({
    Key? key,
    this.file,
    this.files,
    this.initialIndex = 0,
    this.fullScreen = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      insetPadding: EdgeInsets.zero,
      child: SafeArea(
        child: Stack(
          children: [
            FilePreviewWidget(
              file: file,
              files: files,
              initialIndex: initialIndex,
            ),
            Positioned(
              top: kIsWeb ? 20 : 40,
              right: 20,
              child: IconButton(
                icon: const Icon(Icons.close, color: Colors.white),
                iconSize: 32,
                onPressed: () {
                  Navigator.of(context).pop();
                },
                style: IconButton.styleFrom(
                  backgroundColor: Colors.black.withOpacity(0.5),
                  shape: const CircleBorder(),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 显示文件预览弹窗的方法
Future<void> showFilePreview({
  required BuildContext context,
  FileInfo? file,
  List<FileInfo>? files,
  int initialIndex = 0,
  bool fullScreen = true,
}) async {
  await showDialog(
    context: context,
    barrierColor: Colors.black,
    builder: (context) => FilePreviewDialog(
      file: file,
      files: files,
      initialIndex: initialIndex,
      fullScreen: fullScreen,
    ),
  );
}